import { Toast, Dialog } from 'vant';
import axios from '../../plugins/http';
import router from '@/router';
export default {
    namespaced: true,
    state() {
        return {
            // 购物车列表
            cartList: []
        }
    },
    mutations: {
        // 更新购物车列表
        cartListInit(state, payload) {
            state.cartList = payload;
        },
        // 删除购物车
        cartDel(state, payload) {
            const index = state.cartList.findIndex(item => item.id === payload);
            state.cartList.splice(index, 1);
        },
        // 添加购物车
        // payload: 商品对象
        cartAdd(state, payload) {
            // 查看当前商品是否存在于购物车中
            const index = state.cartList.findIndex(item => item.id == payload.goodsid);
            if (index > -1) {
                // 存在, 则值修改商品数量+1
                state.cartList[index].num += 1;
            } else {
                // 不存在, 需要在购物车列表数组中插入一条商品数据
                // 计算购物车id
                const len = state.cartList.length;
                const id = len > 0 ? state.cartList[len - 1].id + 1 : 1;
                // 构造商品对象
                const goods = {
                    id, ...payload
                }
                // 将商品对象追加到购物车列表数组的末尾
                state.cartList.push(goods);
            }
            Toast('加入购物车成功!');
        },
        // 更新全选复选框的状态
        updateAllChecked(state, payload) {
            // 更新每一个商品选中状态
            state.cartList.forEach(item => {
                item.status = payload;
            });
        },
    },
    actions: {
        // 添加购物车
        async cartAddAction({ dispatch }, payload) {
            const { uid } = JSON.parse(localStorage.getItem('userLoginInfo') || '{}');
            if (!uid) {
                const result = await Dialog.confirm({
                    title: '提示',
                    message: '您还没有登录, 确认登录?',
                }).catch(() => null);
                if (result) {
                    router.push({ name: "login", query: { url: router.currentRoute.fullPath } });
                }
                return false;
            }
            axios.post('/cartadd', { uid, ...payload }).then(res => {
                if (res.code === 200) {
                    Toast(res.msg);
                    dispatch('getCartList');
                }
            });
        },
        // 更新所有商品的选中状态
        updateAllChecked({ commit }, payload) {
            const { uid } = JSON.parse(localStorage.getItem("userLoginInfo") || '{}');
            const status = payload ? 1 : 0;
            axios.post('/cartUpdateAllChecked', { uid, status }).then((res) => {
                if (res.code === 200) {
                    commit('updateAllChecked', status);
                }
            });
        },
        // 请求购物车列表
        getCartList({ commit }, callback) {
            const { uid } = JSON.parse(localStorage.getItem('userLoginInfo') || '{}');
            if (!uid) {
                return Toast('您还没有登录');
            }
            axios.get('/cartlist', { params: { uid } }).then(res => {
                if (res.code === 200) {
                    commit('cartListInit', res.list ? res.list : []);
                    setTimeout(() => {
                        callback && callback();
                    }, 300);
                }
            });
        },
        // 删除购物车商品
        cartDelAction({ commit }, payload) {
            axios.post('/cartdelete', { id: payload }).then(res => {
                if (res.code === 200) {
                    commit('cartDel', payload);
                }
            });
        }
    },
    getters: {
        // 计算购物车商品总数
        cartGoodsCount(state) {
            let count = 0;
            state.cartList.forEach(item => {
                if (item.status == 1) {
                    count += item.num;
                }
            });
            return count;
        },
        // 计算购物车总价
        cartPrice(state) {
            let price = 0;
            state.cartList.forEach(item => {
                if (item.status == 1) {
                    price += item.price * item.num;
                }
            });
            // 将计算单位改为分
            return parseFloat(price * 100);
        },
        // 计算全选复选框选中状态
        originAllChecked(state) {
            let checked = true;
            state.cartList.forEach(item => {
                if (item.status == 0) {
                    checked = false;
                }
            });
            return checked;
        }
    }
}